layui.define(['jquery','upload'], function(exports){

    var $ = layui.jquery;
    var upload = layui.upload;

    $('body').on('click', '[data-image]', function () {
        var title = $(this).attr('data-image'),
            src = $(this).attr('src'),
            alt = $(this).attr('alt');
        var photos = {
            "title": title,
            "id": Math.random(),
            "data": [
                {
                    "alt": alt,
                    "pid": Math.random(),
                    "src": src,
                    "thumb": src
                }
            ]
        };
        layer.photos({
            photos: photos,
            anim: 5
        });
        return false;
    });

    var init = {
        upload_url: '/system/upload/add_ajax',
        upload_exts: 'doc|gif|ico|icon|jpg|mp3|mp4|p12|pem|png|rar|ttf|otf|zip|tar|apk',
    };

    var obj = {

        time:function(d, format){

                var timetemp = d * 1000;

                var digit = function(num, length, end){
                    var str = '';
                    num = String(num);
                    length = length || 2;
                    for(var i = num.length; i < length; i++){
                        str += '0';
                    }
                    return num < Math.pow(10, length) ? str + (num|0) : num;
                };

                var date = new Date(timetemp || new Date())
                    ,ymd = [
                    digit(date.getFullYear(), 4)
                    ,digit(date.getMonth() + 1)
                    ,digit(date.getDate())
                ]
                    ,hms = [
                    digit(date.getHours())
                    ,digit(date.getMinutes())
                    ,digit(date.getSeconds())
                ];

                format =  'yyyy-MM-dd HH:mm:ss';

                return format.replace(/yyyy/g, ymd[0])
                    .replace(/MM/g, ymd[1])
                    .replace(/dd/g, ymd[2])
                    .replace(/HH/g, hms[0])
                    .replace(/mm/g, hms[1])
                    .replace(/ss/g, hms[2]);
        },
        image: function (data, title) {
           var imageWidth = 200;
           var imageHeight =  40;
           var imageSplit =  '|';
           var imageJoin =  '<br>';
           var title =  title;

           var value = data;

            if (value === undefined || value===null) {
                return '<img style="max-width: ' + imageWidth + 'px; max-height: ' + imageHeight + 'px;" src="' + value + '" data-image="' + title + '">';
            } else {
                var values = value.split(imageSplit),
                    valuesHtml = [];
                values.forEach((value, index) => {
                    valuesHtml.push('<img style="max-width: ' + imageWidth + 'px; max-height: ' + imageHeight + 'px;" src="' + value + '" data-image="' + title + '">');
                });
                return valuesHtml.join(imageJoin);
            }
        },

        config: {
            shade: [0.02, '#000'],
        },
        request: {
            post: function (option, ok, no, ex) {
                return obj.request.ajax('post', option, ok, no, ex);
            },
            get: function (option, ok, no, ex) {
                return obj.request.ajax('get', option, ok, no, ex);
            },
            ajax: function (type, option, ok, no, ex) {
                type = type || 'get';
                option.url = option.url || '';
                option.data = option.data || {};
                option.prefix = option.prefix || false;
                option.statusName = option.statusName || 'code';
                option.statusCode = option.statusCode || 200;
                ok = ok || function (res) {
                };
                no = no || function (res) {

                    var msg = res.msg == undefined ? '返回数据格式有误' : res.msg;
                    obj.msg.error(msg);
                    return false;
                };
                ex = ex || function (res) {
                };
                if (option.url == '') {
                    obj.msg.error('请求地址不能为空');
                    return false;
                }
                if (option.prefix == true) {
                    option.url = obj.url(option.url);
                }
                var index = obj.msg.loading('加载中');
                $.ajax({
                    url: option.url,
                    type: type,
                    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                    dataType: "json",
                    data: option.data,
                    timeout: 60000,
                    success: function (res) {
                        obj.msg.close(index);
                        if (eval('res.' + option.statusName) == option.statusCode) {
                            return ok(res);
                        } else {
                            return no(res);
                        }
                    },
                    error: function (xhr, textstatus, thrown) {
                        obj.msg.error('Status:' + xhr.status + '，' + xhr.statusText + '，请稍后再试！', function () {
                            ex(this);
                        });
                        return false;
                    }
                });
            }
        },
        msg: {
            // 成功消息
            success: function (msg, callback) {
                if (callback === undefined) {
                    callback = function () {
                    }
                }
                var index = layer.msg(msg, {
                    icon: 1,
                    shade: obj.config.shade,
                    scrollbar: false,
                    time: 2000,
                    shadeClose: true
                }, callback);
                return index;
            },
            // 失败消息
            error: function (msg, callback) {
                if (callback === undefined) {
                    callback = function () {
                    }
                }
                var index = layer.msg(msg, {
                    icon: 2,
                    shade: obj.config.shade,
                    scrollbar: false,
                    time: 3000,
                    shadeClose: true
                }, callback);
                return index;
            },
            // 警告消息框
            alert: function (msg, callback) {
                var index = layer.alert(msg, {end: callback, scrollbar: false});
                return index;
            },
            // 对话框
            confirm: function (msg, ok, no) {
                var index = layer.confirm(msg, {title: '操作确认', btn: ['确认', '取消']}, function () {
                    typeof ok === 'function' && ok.call(this);
                }, function () {
                    typeof no === 'function' && no.call(this);
                    self.close(index);
                });
                return index;
            },
            // 消息提示
            tips: function (msg, time, callback) {
                var index = layer.msg(msg, {
                    time: (time || 3) * 1000,
                    shade: this.shade,
                    end: callback,
                    shadeClose: true
                });
                return index;
            },
            // 加载中提示
            loading: function (msg, callback) {
                var index = msg ? layer.msg(msg, {
                    icon: 16,
                    scrollbar: false,
                    shade: this.shade,
                    time: 0,
                    end: callback
                }) : layer.load(2, {time: 0, scrollbar: false, shade: this.shade, end: callback});
                return index;
            },
            // 关闭消息框
            close: function (index) {
                return layer.close(index);
            }

        },
        api:{
            upload: function () {
                var uploadList = document.querySelectorAll("[data-upload]");
                if (uploadList.length > 0) {
                    $.each(uploadList, function (i, v) {
                        var exts = $(this).attr('data-upload-exts'),
                            uploadName = $(this).attr('data-upload'),
                            uploadNumber = $(this).attr('data-upload-number'),
                            uploadSign = $(this).attr('data-upload-sign');
                        exts = exts || init.upload_exts;
                        uploadNumber = uploadNumber || 'one';
                        uploadSign = uploadSign || '|';
                        var elem = "input[name='" + uploadName + "']",
                            uploadElem = this;

                        // 监听上传事件
                        upload.render({
                            elem: this,
                            url: init.upload_url,
                            accept: 'file',
                            exts: exts,
                            // 让多图上传模式下支持多选操作
                            multiple: (uploadNumber !== 'one') ? true : false,
                            done: function (res) {
                                if (res.code === 200) {
                                    var url = res.data.url;
                                    if (uploadNumber !== 'one') {
                                        var oldUrl = $(elem).val();
                                        if (oldUrl !== '') {
                                            url = oldUrl + uploadSign + url;
                                        }
                                    }
                                    $(elem).val(url);
                                    $(elem).trigger("input");
                                    obj.msg.success(res.msg);
                                } else {
                                    obj.msg.error(res.msg);
                                }
                                return false;
                            }
                        });

                        if(exts == 'png|jpg|ico|jpeg'){
                            // 监听上传input值变化
                            $(elem).bind("input propertychange", function (event) {
                                var urlString = $(this).val(),
                                    urlArray = urlString.split(uploadSign),
                                    uploadIcon = $(uploadElem).attr('data-upload-icon');
                                uploadIcon = uploadIcon || "file";

                                $('#bing-' + uploadName).remove();


                                if (urlString.length > 0 ) {
                                    var parant = $(this).parent('div');
                                    var liHtml = '';
                                    $.each(urlArray, function (i, v) {
                                        liHtml += '<li><a><img class="path_" src="' + v + '" style="max-width: 180px;" data-image></a><small class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                                    });
                                    parant.after('<ul id="bing-' + uploadName + '" class="layui-input-block layuimini-upload-show">\n' + liHtml + '</ul>');
                                }

                            });

                            // 非空初始化图片显示
                            if ($(elem).val() !== '') {
                                $(elem).trigger("input");
                            }
                        }

                    });

                    // 监听上传文件的删除事件
                    $('body').on('click', '[data-upload-delete]', function () {
                        var uploadName = $(this).attr('data-upload-delete'),
                            deleteUrl = $(this).attr('data-upload-url'),
                            sign = $(this).attr('data-upload-sign');
                        var confirm = obj.msg.confirm('确定删除？', function () {
                            var elem = "input[name='" + uploadName + "']";
                            var currentUrl = $(elem).val();
                            var url = '';
                            if (currentUrl !== deleteUrl) {
                                url = currentUrl.search(deleteUrl) === 0 ? currentUrl.replace(deleteUrl + sign, '') : currentUrl.replace(sign + deleteUrl, '');
                                $(elem).val(url);
                                $(elem).trigger("input");
                            } else {
                                $(elem).val(url);
                                $('#bing-' + uploadName).remove();
                            }
                            obj.msg.close(confirm);
                        });
                        return false;
                    });
                }
            }
        }
    };
    //输出接口
    exports('sh', obj);

});
